import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _isEmpty from "lodash/isEmpty";
var _excluded = ["level"];

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10, _dec11, _dec12, _dec13, _class, _class2;

/**
 * Client - 客户端
 * @date: 2018-12-24

 * @version: 1.0.0

 */
import React from 'react';
import { connect } from 'dva';
import { Form, Input, Button, Table, Tag, Row, Col } from 'antd';
import { Bind } from 'lodash-decorators';
import { SEARCH_COL_CLASSNAME, SEARCH_FORM_ROW_LAYOUT, FORM_COL_4_LAYOUT, SEARCH_FORM_ITEM_LAYOUT } from 'utils/constants';
import intl from 'utils/intl';
import formatterCollections from 'utils/intl/formatterCollections';
import notification from 'utils/notification';
import { Content, Header } from 'components/Page';
import { Button as ButtonPermission } from 'components/Permission';
import { isTenantRoleLevel, getCurrentOrganizationId, tableScrollWidth } from 'utils/utils';
import { enableRender, operatorRender } from 'utils/renderer';
import Lov from 'components/Lov';
import Drawer from "./Drawer";
var FormItem = Form.Item;
var Client = (_dec = connect(function (_ref) {
  var loading = _ref.loading,
      client = _ref.client;
  return {
    client: client,
    fetchListLoading: loading.effects['client/fetchClientList'],
    fetchDetailLoading: loading.effects['client/fetchDetail'],
    createLoading: loading.effects['client/createClient'],
    updateLoading: loading.effects['client/updateClient'],
    loadingDistributeUsers: loading.effects['client/roleQueryAll'],
    // 查询可分配的所有角色
    fetchOwnedLoading: loading.effects['client/roleCurrent'],
    saveRoleLoading: loading.effects['client/saveRoleSet'],
    tenantId: getCurrentOrganizationId(),
    isTenant: isTenantRoleLevel()
  };
}), _dec2 = formatterCollections({
  code: ['ciam.client', 'entity.tenant', 'ciam.roleManagement']
}), _dec3 = Form.create({
  fieldNameProp: null
}), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Bind(), _dec7 = Bind(), _dec8 = Bind(), _dec9 = Bind(), _dec10 = Bind(), _dec11 = Bind(), _dec12 = Bind(), _dec13 = Bind(), _dec(_class = _dec2(_class = _dec3(_class = (_class2 = /*#__PURE__*/function (_React$Component) {
  _inherits(Client, _React$Component);

  var _super = _createSuper(Client);

  function Client() {
    var _this;

    _classCallCheck(this, Client);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));
    _this.state = {
      visible: false,
      // 测试弹窗
      detailStatus: 'create' // the detail's status

    };
    return _this;
  }

  _createClass(Client, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var dispatch = this.props.dispatch;
      dispatch({
        type: 'client/queryType'
      });
      this.handleSearch();
      this.fetchPublicKey();
    }
    /**
     * 请求公钥
     */

  }, {
    key: "fetchPublicKey",
    value: function fetchPublicKey() {
      var _this$props$dispatch = this.props.dispatch,
          dispatch = _this$props$dispatch === void 0 ? function () {} : _this$props$dispatch;
      dispatch({
        type: 'client/getPublicKey'
      });
    }
    /**
     * 查询
     * @param {object} fields - 查询参数
     */

  }, {
    key: "handleSearch",
    value: function handleSearch() {
      var fields = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var _this$props = this.props,
          form = _this$props.form,
          dispatch = _this$props.dispatch,
          tenantId = _this$props.tenantId;
      form.validateFields(function (err, values) {
        var fieldValues = values || {};

        if (!err) {
          dispatch({
            type: 'client/fetchClientList',
            payload: _objectSpread({
              page: _isEmpty(fields) ? {} : fields,
              tenantId: tenantId
            }, fieldValues)
          });
        }
      });
    }
    /**
     * @function handleResetSearch - 重置查询表单
     */

  }, {
    key: "handleResetSearch",
    value: function handleResetSearch() {
      this.props.form.resetFields();
    } // 打开连接测试弹窗

  }, {
    key: "showModal",
    value: function showModal() {
      this.setState({
        visible: true
      });
    } // 关闭连接测试弹窗

  }, {
    key: "hiddenModal",
    value: function hiddenModal() {
      this.setState({
        visible: false
      });
    } // 新建

  }, {
    key: "handleAdd",
    value: function handleAdd() {
      var dispatch = this.props.dispatch; // 新建的时候清空详情的数据 防止 编辑 => 新建 后 将编辑的数据传给后台

      dispatch({
        type: 'client/updateState',
        payload: {
          detailData: {}
        }
      });
      this.setState({
        detailStatus: 'create',
        visible: true
      });
    } // fetch detail data

  }, {
    key: "fetchDetailData",
    value: function fetchDetailData(record) {
      var _this$props2 = this.props,
          dispatch = _this$props2.dispatch,
          tenantId = _this$props2.tenantId;
      return dispatch({
        type: 'client/fetchDetail',
        payload: {
          tenantId: tenantId,
          clientId: record.id
        }
      });
    } // 编辑

  }, {
    key: "handleUpdate",
    value: function handleUpdate(record) {
      this.setState({
        detailRecord: record,
        detailStatus: 'update',
        visible: true
      });
    } // 保存

  }, {
    key: "handleSave",
    value: function handleSave(fieldsValue) {
      var _this2 = this;

      var _this$props3 = this.props,
          dispatch = _this$props3.dispatch,
          _this$props3$client = _this$props3.client,
          pagination = _this$props3$client.pagination,
          _this$props3$client$d = _this$props3$client.detailData,
          detailData = _this$props3$client$d === void 0 ? {} : _this$props3$client$d,
          tenantId = _this$props3.tenantId;
      var id = detailData.id;
      var authorizedGrantTypes = fieldsValue.authorizedGrantTypes,
          scope = fieldsValue.scope,
          autoApprove = fieldsValue.autoApprove;
      var grantTypes;
      var scopeT;
      var autoApproveT;

      if (authorizedGrantTypes) {
        grantTypes = authorizedGrantTypes.join(',');
      }

      if (scope) {
        scopeT = scope.join(',');
      }

      if (autoApprove) {
        autoApproveT = autoApprove.join(',');
      } // TODO: 保存时保存编辑客户端分配角色


      dispatch({
        type: "client/".concat(id ? 'updateClient' : 'createClient'),
        payload: _objectSpread(_objectSpread(_objectSpread({
          tenantId: tenantId
        }, detailData), fieldsValue), {}, {
          authorizedGrantTypes: grantTypes,
          scope: scopeT,
          autoApprove: autoApproveT,
          clientId: id
        })
      }).then(function (res) {
        if (res) {
          notification.success();

          _this2.hiddenModal();

          _this2.handleSearch(pagination);
        }
      });
    }
    /**
     * 数据列表，删除
     * @param {obejct} record - 操作对象
     */
    // @Bind()
    // handleDeleteContent(record) {
    //   const {
    //     dispatch,
    //     tenantId,
    //     client: { pagination },
    //   } = this.props;
    //   dispatch({
    //     type: 'client/deleteClient',
    //     payload: { tenantId, ...record },
    //   }).then(res => {
    //     if (res) {
    //       notification.success();
    //       this.handleSearch(pagination);
    //     }
    //   });
    // }

    /**
     * @function renderForm - 渲染搜索表单
     */

  }, {
    key: "renderFilterForm",
    value: function renderFilterForm() {
      var getFieldDecorator = this.props.form.getFieldDecorator;
      var isTenant = this.props.isTenant;
      return /*#__PURE__*/React.createElement(Form, null, /*#__PURE__*/React.createElement(Row, Object.assign({
        type: "flex",
        gutter: 24,
        align: "bottom"
      }, SEARCH_FORM_ROW_LAYOUT), !isTenant && /*#__PURE__*/React.createElement(Col, FORM_COL_4_LAYOUT, /*#__PURE__*/React.createElement(FormItem, Object.assign({
        label: intl.get('entity.tenant.tag').d('租户')
      }, SEARCH_FORM_ITEM_LAYOUT), getFieldDecorator('organizationId')( /*#__PURE__*/React.createElement(Lov, {
        code: "CPFM.TENANT",
        textField: "tenantName"
      })))), /*#__PURE__*/React.createElement(Col, FORM_COL_4_LAYOUT, /*#__PURE__*/React.createElement(FormItem, Object.assign({}, SEARCH_FORM_ITEM_LAYOUT, {
        label: intl.get('ciam.client.model.client.name').d('名称')
      }), getFieldDecorator('name', {})( /*#__PURE__*/React.createElement(Input, null)))), /*#__PURE__*/React.createElement(Col, Object.assign({}, FORM_COL_4_LAYOUT, {
        className: SEARCH_COL_CLASSNAME
      }), /*#__PURE__*/React.createElement(FormItem, null, /*#__PURE__*/React.createElement(Button, {
        onClick: this.handleResetSearch
      }, intl.get('cpaas.common.button.reset').d('重置')), /*#__PURE__*/React.createElement(Button, {
        type: "primary",
        htmlType: "submit",
        onClick: this.handleSearch
      }, intl.get('cpaas.common.button.search').d('查询'))))));
    } // 查询所有可分配的角色

  }, {
    key: "fetchAllRoles",
    value: function fetchAllRoles(fields) {
      var level = fields.level,
          rest = _objectWithoutProperties(fields, _excluded);

      var dispatch = this.props.dispatch;
      return dispatch({
        type: 'client/roleQueryAll',
        payload: _objectSpread({}, rest)
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this3 = this;

      var _this$props4 = this.props,
          path = _this$props4.match.path,
          dispatch = _this$props4.dispatch,
          tenantId = _this$props4.tenantId,
          client = _this$props4.client,
          createLoading = _this$props4.createLoading,
          updateLoading = _this$props4.updateLoading,
          fetchListLoading = _this$props4.fetchListLoading,
          fetchRandomLoading = _this$props4.fetchRandomLoading,
          fetchDetailLoading = _this$props4.fetchDetailLoading,
          loadingDistributeUsers = _this$props4.loadingDistributeUsers,
          fetchOwnedLoading = _this$props4.fetchOwnedLoading,
          saveRoleLoading = _this$props4.saveRoleLoading,
          isTenant = _this$props4.isTenant;
      var _client$clientList = client.clientList,
          clientList = _client$clientList === void 0 ? [] : _client$clientList,
          pagination = client.pagination,
          _client$typeList = client.typeList,
          typeList = _client$typeList === void 0 ? [] : _client$typeList,
          paginationRole = client.paginationRole,
          _client$detailData = client.detailData,
          detailData = _client$detailData === void 0 ? {} : _client$detailData,
          _client$levelMap = client.levelMap,
          levelMap = _client$levelMap === void 0 ? {} : _client$levelMap,
          publicKey = client.publicKey,
          _client$visitRoleList = client.visitRoleList,
          visitRoleList = _client$visitRoleList === void 0 ? [] : _client$visitRoleList,
          _client$visitRolePagi = client.visitRolePagination,
          visitRolePagination = _client$visitRolePagi === void 0 ? {} : _client$visitRolePagi;
      var _this$state = this.state,
          visible = _this$state.visible,
          _this$state$detailSta = _this$state.detailStatus,
          detailStatus = _this$state$detailSta === void 0 ? 'create' : _this$state$detailSta,
          _this$state$detailRec = _this$state.detailRecord,
          detailRecord = _this$state$detailRec === void 0 ? {} : _this$state$detailRec;
      var columns = [!isTenant && {
        title: intl.get('cpaas.common.model.common.tenantId').d('租户'),
        dataIndex: 'tenantName',
        width: 200
      }, {
        title: intl.get('ciam.client.model.client.name').d('名称'),
        dataIndex: 'name',
        width: 200
      }, {
        title: intl.get('ciam.client.model.client.authorizedGrantTypes').d('授权类型'),
        dataIndex: 'authorizedGrantTypes',
        // width: 200,
        render: function render(text) {
          var typeListT = text.split(',') || [];
          return typeListT.map(function (item) {
            return /*#__PURE__*/React.createElement(Tag, {
              key: item
            }, item);
          });
        }
      }, {
        title: intl.get('cpaas.common.status').d('状态'),
        width: 100,
        dataIndex: 'enabledFlag',
        render: enableRender
      }, {
        title: intl.get('cpaas.common.button.action').d('操作'),
        key: 'operation',
        width: 120,
        fixed: 'right',
        render: function render(text, record) {
          var operators = [{
            key: 'edit',
            ele: /*#__PURE__*/React.createElement("a", {
              onClick: function onClick() {
                return _this3.handleUpdate(record);
              }
            }, intl.get('cpaas.common.button.edit').d('编辑')),
            len: 2,
            title: intl.get('cpaas.common.button.edit').d('编辑')
          }];
          return operatorRender(operators);
        }
      }].filter(Boolean);
      var title = detailStatus === 'create' ? intl.get('cpaas.common.button.create').d('新建') : intl.get('cpaas.common.button.edit').d('编辑');
      var drawerProps = {
        path: path,
        dispatch: dispatch,
        tenantId: tenantId,
        title: title,
        typeList: typeList,
        visible: visible,
        loadingDistributeUsers: loadingDistributeUsers,
        fetchOwnedLoading: fetchOwnedLoading,
        saveRoleLoading: saveRoleLoading,
        paginationRole: paginationRole,
        detailRecord: detailRecord,
        // current edit record
        detailStatus: detailStatus,
        // current edit status
        loading: createLoading || updateLoading || fetchDetailLoading || fetchRandomLoading,
        fetchLoading: fetchDetailLoading || fetchRandomLoading,
        initData: detailData,
        onCancel: this.hiddenModal,
        onOk: this.handleSave,
        fetchAllRoles: this.fetchAllRoles,
        fetchDetailData: this.fetchDetailData,
        isTenantRoleLevel: isTenant,
        levelMap: levelMap,
        publicKey: publicKey,
        visitRoleList: visitRoleList,
        visitRolePagination: visitRolePagination
      };
      return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Header, {
        title: intl.get('ciam.client.view.message.title.list').d('客户端')
      }, /*#__PURE__*/React.createElement(ButtonPermission, {
        permissionList: [{
          code: "".concat(path, ".button.create"),
          type: 'button',
          meaning: '客户端-新建'
        }],
        icon: "plus",
        type: "primary",
        onClick: this.handleAdd
      }, intl.get('cpaas.common.button.create').d('新建'))), /*#__PURE__*/React.createElement(Content, null, /*#__PURE__*/React.createElement("div", {
        className: "table-list-search"
      }, this.renderFilterForm()), /*#__PURE__*/React.createElement(Table, {
        bordered: true,
        rowKey: "id",
        loading: fetchListLoading,
        dataSource: clientList,
        columns: columns,
        scroll: {
          x: tableScrollWidth(columns, 400)
        },
        pagination: pagination,
        onChange: this.handleSearch
      }), visible && /*#__PURE__*/React.createElement(Drawer, drawerProps)));
    }
  }]);

  return Client;
}(React.Component), (_applyDecoratedDescriptor(_class2.prototype, "fetchPublicKey", [_dec4], Object.getOwnPropertyDescriptor(_class2.prototype, "fetchPublicKey"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleSearch", [_dec5], Object.getOwnPropertyDescriptor(_class2.prototype, "handleSearch"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleResetSearch", [_dec6], Object.getOwnPropertyDescriptor(_class2.prototype, "handleResetSearch"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "showModal", [_dec7], Object.getOwnPropertyDescriptor(_class2.prototype, "showModal"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "hiddenModal", [_dec8], Object.getOwnPropertyDescriptor(_class2.prototype, "hiddenModal"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleAdd", [_dec9], Object.getOwnPropertyDescriptor(_class2.prototype, "handleAdd"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "fetchDetailData", [_dec10], Object.getOwnPropertyDescriptor(_class2.prototype, "fetchDetailData"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleUpdate", [_dec11], Object.getOwnPropertyDescriptor(_class2.prototype, "handleUpdate"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleSave", [_dec12], Object.getOwnPropertyDescriptor(_class2.prototype, "handleSave"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "fetchAllRoles", [_dec13], Object.getOwnPropertyDescriptor(_class2.prototype, "fetchAllRoles"), _class2.prototype)), _class2)) || _class) || _class) || _class);
export { Client as default };